/*
 * Copyright (c) kecp
 * Build on May 14, 2010
 */

package LBS;

import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.io.*;
import javax.microedition.lcdui.Image;

/**
 * 谷歌静态地图服务
 * 获取指定地点、指定范围内的地图图片
 * @author kecp
 */
public class GoogleMap {
    static final String apiKey = "ABQIAAAAZABhYSnajVLwjSViLnCMaRSyyI-jLT78wquFE6TGkdZmN7x1jBT8QHTgOuj88-Ec7LHtmlwsAPoMIg"; //regist website: http://code.google.com/p/nearby/

    /** 缩放级别 */
    short zoom = 10 ;
    int width = 320;
    int height =240;
    String format = "JPEG";
    String maptype = "mobile";
    String sensor = "false";

    /**
     * 发送请求并得到一张地图图片
     * @param url 请求
     * @return 图片
     * @throws IOException
     */
    private Image sendHttpGetImg( String url ) throws IOException {

        HttpConnection hcon = null;
        DataInputStream dis = null;

        StringBuffer message = new StringBuffer();
        hcon = ( HttpConnection ) Connector.open( url );
        dis = new DataInputStream( hcon.openInputStream() );

        Image img = Image.createImage(dis);
        return img;

    }

    private String getCenter(Location loc ){
        String str;
        str = String.valueOf( loc.getLat() ) + ',' + String.valueOf( loc.getLon() );
        return str;
    }

    /**
     * 将坐标转换为地图请求
     * @param loc
     * @return 请求url
     */
    private String makeUrl (Location loc ){

        StringBuffer sb = new StringBuffer("http://maps.google.com/maps/api/staticmap?");
        sb.append("center").append("=").append(getCenter(loc));
        sb.append("&size=").append(width).append('x').append(height);
        sb.append("&sensor=").append(sensor);
        sb.append("&zoom=").append(zoom);
        sb.append("&format=").append(format);
        sb.append("&maptype=").append(maptype);

        return sb.toString();
    }

    /**
     * 获取指定坐标为中心的地图图片
     * @param loct 坐标
     * @return  图片
     */
    public Image getImg( Location loct ) {
        String url = makeUrl(loct);
        Image img = null;
        //System.out.println(url);
        try {
            img =sendHttpGetImg(url);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return img;
    }

    public static Image testGetImg(){
        GoogleMap gm = new GoogleMap();
        Image img = null;
        Location loc = Location.getTestLocation();
        //String url =  "http://maps.google.com/maps/api/staticmap?center=51.507161393258,-0.11857605617978&zoom=14&size=600x400&sensor=false";
        String url = gm.makeUrl(loc);
        System.out.println(url);
        try {
            img = gm.sendHttpGetImg(url);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return img;
    }
}
